package views

import (
	"strconv"
	"net/http"
	"appengine"
	"mdbook/model/post"
)

func XhrGetPostHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	query := r.URL.Query()
	ver, _ := strconv.ParseInt(query.Get("ver"), 10, 64)
	p, err := post.Get(query.Get("path"), ver, ctx)
	if err != nil {
		ctx.Errorf("XHR GET POST ERROR: %v", err)
		renderJSON(w, r, p)
		return
	}
	renderJSON(w, r, p)
}

func XhrNewPostHandler(w http.ResponseWriter, r *http.Request){
	ctx := appengine.NewContext(r)
	page, err := post.New(r.FormValue("path"), r.FormValue("text"), r.FormValue("title"), ctx)
	if err != nil {
		ctx.Errorf("XHR NEW POST ERROR: %v", err)
		renderJSON(w, r, err)
		return
	}
	renderJSON(w, r, page)
}

func XhrGetPostsHandler(w http.ResponseWriter, r *http.Request){
	ctx := appengine.NewContext(r)
	query := r.URL.Query()
	offset, _ := strconv.Atoi(query.Get("offset"))
	limit, _ := strconv.Atoi(query.Get("limit"))
	order := query.Get("order");
	if order == "" {
		order = "-Id"
	}
	ps, err := post.GetPosts(offset, limit, order, ctx)
	if err != nil {
		renderJSON(w, r, err)
		return
	}
	renderJSON(w, r, ps)
}

func XhrGetMaxHandler(w http.ResponseWriter, r *http.Request){
	ctx := appengine.NewContext(r)
	max, err := post.GetMaxId(ctx)
	if err != nil {
		renderJSON(w, r, err)
		return
	}
	renderJSON(w, r, &post.Path{Id:max})
}

func XhrSetPathHandler(w http.ResponseWriter, r *http.Request){
	ctx := appengine.NewContext(r)
	path := r.FormValue("path")
	npath := r.FormValue("npath")
	p, err := post.NewUrl(path, npath, ctx)
	if err != nil {
		ctx.Errorf("new path url error: %v", err)
		renderJSON(w, r, err)
		return
	}
	renderJSON(w, r, p)
}
